<?php

namespace app\api\service\admin;

use app\common\library\Auth;
use think\Validate;
use think\Db;

class ScheduleService
{
    // 列表
    public static function index($data)
    {
        $auth = Auth::instance();
        $type  = $data['type'];
        $date = $data['date'];
        $studios_id = $data['studios_id'];
        $teacher_id = $auth->id;

        if($type == 'day'){
            $Schedule = self::getDailySchedule($date, $studios_id, $teacher_id);
        }
        if($type == 'week'){
            $Schedule = self::getWeeklySchedule($date, $studios_id, $teacher_id);
        }
        if($type == 'month'){
            $Schedule = self::getMonthlySchedule($date, $studios_id, $teacher_id);
        }
        if($type == 'semester'){
            $Schedule = self::getSemesterSchedule($date, $studios_id, $teacher_id);
        }
        return $Schedule;
    }

    // 添加
    public static function add($data)
    {
        // 验证规则
        $validate = new Validate([
            'studios_id' => 'require',
            'category_id' => 'require',
            'level_id' => 'require',
            'subject_id' => 'require',
            'lesson_codes' => 'require',
            'number_lesson' => 'require',
            'teacher_id' => 'require',
            'date' => 'require',
            'class_id' => 'require',
            'room' => 'require',
            'start' => 'require',
            'end' => 'require',
            'repetition_method' => 'require',
        ], [
            'studios_id.require' => 'StudiosId is not empty',
            'category_id.require' => 'CategoryId is not empty',
            'level_id.require' => 'LevelId is not empty',
            'subject_id.require' => 'SubjectId is not empty',
            'lesson_codes.require' => 'Lesson Codes is not empty',
            'number_lesson.require' => 'Number Lesson is not empty',
            'teacher_id.require' => 'Teacher Id is not empty',
            'date.require' => 'Date is not empty',
            'class_id.require' => 'ClassId is not empty',
            'room.require' => 'Room is not empty',
            'start.require' => 'Start Time is not empty',
            'end.require' => 'End Time is not empty',
            'repetition_method.require' => 'Repetition Method is not empty',
        ]);
        if($data['repetition_method'] == 'daily'){
            $validate = new Validate([
                'ending_method' => 'require',
            ],[
                'ending_method.require' => 'Ending Method is not empty',
            ]);
        }

        if($data['repetition_method'] == 'daily'){
            $validate = new Validate([
                'ending_method' => 'require',
            ],[
                'ending_method.require' => 'Ending Method is not empty',
            ]);
        }

        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务将数据保存到数据库
        try {
            // 按天排课
            if($data['repetition_method'] == 'daily' &&  $data['ending_method'] == 'no end'){
                $data['start_time'] = strtotime($data['date'] . $data['start']);
                $data['end_time'] = strtotime($data['date'] . $data['end']);
                $level_abbr = \app\admin\model\StudentCourseLevel::where(['level_id'=>$data['level_id']])->value('abbreviation');
                // 解析起始课程代码 - 去除level_abbr前缀
                $initialCode = str_replace($level_abbr.'-', '', $data['lesson_codes']);
                $lesson_id = \app\admin\model\StudentLessonCodes::where(['code'=>$initialCode])->value('lesson_id');

                $scheduleData = [
                    'studios_id' => $data['studios_id'],
                    'category_id' => $data['category_id'],
                    'level_id' => $data['level_id'],
                    'subject_id' => $data['subject_id'],
                    'lesson_id' => $lesson_id,
                    'lesson_codes' => $data['lesson_codes'],
                    'number_lesson' => $data['number_lesson'],
                    'teacher_id' => $data['teacher_id'],
                    'date' => $data['date'],
                    'class_id' => $data['class_id'],
                    'room' => $data['room'],
                    'start' => $data['start'],
                    'end' => $data['end'],
                    'start_time' => $data['start_time'],
                    'end_time' => $data['end_time'],
                    'scene' => 1,
                ];
//                return $data;
                $result = \app\admin\model\Schedule::create($scheduleData);
            }
            if($data['repetition_method'] == 'daily' &&  $data['ending_method'] == 'limit times'){
                $data['scene'] = 1;
                if(!$data['total_number_of_lesson']) return ['code'=>400, 'msg'=>'Enter the number of Lessons to Generate', 'state'=>'INVALID_ARGUMENT', 'data'=>null];

                $scheduleData = [];
                $baseDate = $data['date'];
                $categoty_abbr = \app\admin\model\StudentCourseCategory::where(['category_id'=>$data['category_id']])->value('abbreviation');
                if($categoty_abbr == 'kids'){
                    $level_abbr = \app\admin\model\StudentCourseLevel::where(['level_id'=>$data['level_id']])->value('abbreviation');
                    $subject_abbr = \app\admin\model\StudentSubject::where(['subject_id'=>$data['subject_id']])->value('abbreviation');

                    // 解析起始课程代码中的数字部分 (如 PE1-ST0102 中的 0102)
                    preg_match('/(\d{2})(\d{2})$/', $data['lesson_codes'], $matches);
                    $startPair1 = intval($matches[1]); // 第一个两位数 (01)
                    $startPair2 = intval($matches[2]); // 第二个两位数 (02)

                    $scheduleData = [];

                    for ($i = 0; $i < $data['total_number_of_lesson']; $i++) {
                        $currentDate = date('Y-m-d', strtotime("+$i days", strtotime($baseDate)));

                        // 计算当前课程的数字对 (每次递增2)
                        $currentPair1 = $startPair1 + $i * 2;
                        $currentPair2 = $startPair2 + $i * 2;

                        // 生成课程代码 (如 PE1-ST0102, PE1-ST0304 等)
                        $lessonCode = sprintf("%s-%s%02d%02d",
                            $level_abbr,
                            $subject_abbr,
                            $currentPair1,
                            $currentPair2
                        );

                        $code = sprintf("%s%02d%02d",
                            $subject_abbr,
                            $currentPair1,
                            $currentPair2
                        );

                        $lesson_id = \app\admin\model\StudentLessonCodes::where(['code'=>$code])->value('lesson_id');

                        // 检查时间冲突
                        $startTimestamp = strtotime($data['start']);
                        $endTimestamp = strtotime($data['end']);

                        $conflict = \app\admin\model\Schedule::where([
                            'room'=>$data['room'],
                            'date'=>$currentDate
                        ])->where(function($query) use ($startTimestamp, $endTimestamp) {
                            $query->where('start_time', 'between', [$startTimestamp, $endTimestamp])
                                ->whereOr('end_time', 'between', [$startTimestamp, $endTimestamp]);
                        })->find();

                        if ($conflict) {
                            $conflictTime = date('H:i', $conflict->start_time) . '-' . date('H:i', $conflict->end_time);
                            return [
                                'code' => 400,
                                'msg' => "{$data['room']} is already occupied during {$conflictTime} on {$currentDate}",
                                'state' => 'CONFLICT',
                                'data' => null
                            ];
                        }

                        $scheduleData[] = [
                            'studios_id' => $data['studios_id'],
                            'category_id' => $data['category_id'],
                            'level_id' => $data['level_id'],
                            'subject_id' => $data['subject_id'],
                            'lesson_id' => $lesson_id,
                            'lesson_codes' => $lessonCode,
                            'number_lesson' => $data['number_lesson'],
                            'teacher_id' => $data['teacher_id'],
                            'date' => $currentDate,
                            'class_id' => $data['class_id'],
                            'room' => $data['room'],
                            'start' => $data['start'],
                            'end' => $data['end'],
                            'start_time' => strtotime("$currentDate " . $data['start']),
                            'end_time' => strtotime("$currentDate " . $data['end']),
                            'scene' => 1,
                        ];
                    }
                }else{
                    $arr = explode('-', $data['lesson_codes']);
                    $codeStart = $arr[0];
                    $baseCode = $codeStart . '-D'; // 课程代码前缀
                    // 获取开始和结束时间的时间戳格式
                    $startTimestamp = strtotime($data['start']);
                    $endTimestamp = strtotime($data['end']);

                    for ($i = 0; $i < $data['total_number_of_lesson']; $i++) {
                        $currentDate = date('Y-m-d', strtotime("+$i days", strtotime($baseDate)));
                        $lessonCode = $baseCode . ($i + 1);

                        // 检查时间冲突
                        $conflict = \app\admin\model\Schedule::where([
                            'room'=>$data['room'],'date'=>$currentDate
                        ])->where(function($query) use ($startTimestamp, $endTimestamp) {
                            // 新课程开始时间在已有课程时间段内
                            $query->where('start_time', 'between', [$startTimestamp, $endTimestamp])
                                ->whereOr('end_time', 'between', [$startTimestamp, $endTimestamp]);// 新课程结束时间在已有课程时间段内
                        })->find();

                        if ($conflict) {
                            $conflictTime = date('H:i', $conflict->start_time) . '-' . date('H:i', $conflict->end_time);
                            return [
                                'code' => 400,
                                'msg' => "{$data['room']} is already occupied during {$conflictTime} on {$currentDate}",
                                'state' => 'CONFLICT',
                                'data' => null
                            ];
                        }

                        $lesson_id = \app\admin\model\StudentLessonCodes::where(['code'=>$lessonCode])->value('lesson_id');

                        $scheduleData[] = [
                            'studios_id' => $data['studios_id'],
                            'category_id' => $data['category_id'],
                            'level_id' => $data['level_id'],
                            'subject_id' => $data['subject_id'],
                            '$lesson_id' => $lesson_id,
                            'lesson_codes' => $lessonCode,
                            'number_lesson' => $data['number_lesson'],
                            'teacher_id' => $data['teacher_id'],
                            'date' => $currentDate,
                            'class_id' => $data['class_id'],
                            'room' => $data['room'],
                            'start_time' => strtotime("$currentDate " . $data['start']),
                            'end_time' => strtotime("$currentDate " . $data['end']),
                            'scene' => 1,
                        ];
                    }
                }

                // 批量插入数据库
                try {
                    Db::startTrans();
                    $result = \app\admin\model\Schedule::insertAll($scheduleData);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR', 'data' => null];
                }

                return ['code' => 200, 'msg' => 'Schedules created successfully', 'state' => 'OK', 'data' => $result];







            }
            if($data['repetition_method'] == 'daily' && $data['ending_method'] == 'limit date'){
                $data['scene'] = 1;
                if(!$data['end_date']) return ['code'=>400, 'msg'=>'Please enter the end date', 'state'=>'INVALID_ARGUMENT', 'data'=>null];

                $category = \app\admin\model\StudentCourseCategory::find($data['category_id']);
                if (!$category) {
                    return ['code' => 404, 'msg' => 'Subject not found', 'state' => 'NOT_FOUND'];
                }
                $isKidsCourse = ($category->abbreviation == 'kids');

                $scheduleData = [];
                $currentDate = $data['date'];
                $endDate = $data['end_date'];
                $dayCount = 0;

                try {
                    Db::startTrans();

                    while (strtotime($currentDate) <= strtotime($endDate)) {
                        $dayCount++;

                        if ($isKidsCourse) {
                            // Kids课程代码生成逻辑 (PE1-ST0102, PE1-ST0304, ...)
                            $level_abbr = \app\admin\model\StudentCourseLevel::where(['level_id'=>$data['level_id']])->value('abbreviation');
                            $subject_abbr = \app\admin\model\StudentSubject::where(['subject_id'=>$data['subject_id']])->value('abbreviation');

                            if($dayCount == 1){
                                $initialCode = $data['lesson_codes'];
                                // 解析初始代码中的数字部分
                                preg_match('/(\d{2})(\d{2})$/', $initialCode, $matches);
                                $currentHour1 = intval($matches[1]);
                                $currentHour2 = intval($matches[2]);
                            } else {
                                // 每小时递增2小时
                                $currentHour1 += 2;
                                $currentHour2 += 2;
                            }

                            $lessonCode = sprintf("%s-%s%02d%02d",
                                $level_abbr,
                                $subject_abbr,
                                $currentHour1,
                                $currentHour2
                            );

                            $code = sprintf("%s%02d%02d",
                                $subject_abbr,
                                $currentHour1,
                                $currentHour2
                            );

                            $lesson_id = \app\admin\model\StudentLessonCodes::where(['code'=>$code])->value('lesson_id');
                        } else {
                            // 非Kids课程代码生成逻辑 (GEJ-D1, GEJ-D2, ...)
                            $arr = explode('-', $data['lesson_codes']);
                            $codeStart = $arr[0];
                            $lessonCode = $codeStart . '-D' . $dayCount;

                            $lesson_id = \app\admin\model\StudentLessonCodes::where(['code'=>$lessonCode])->value('lesson_id');
                        }

                        // 检查时间冲突
                        $startTimestamp = strtotime($currentDate . ' ' . $data['start']);
                        $endTimestamp = strtotime($currentDate . ' ' . $data['end']);

                        $conflict = \app\admin\model\Schedule::where([
                            'room' => $data['room'],
                            'date' => $currentDate
                        ])->where(function($query) use ($startTimestamp, $endTimestamp) {
                            $query->where('start_time', 'between', [$startTimestamp, $endTimestamp])
                                ->whereOr('end_time', 'between', [$startTimestamp, $endTimestamp]);
                        })->find();

                        if ($conflict) {
                            Db::rollback();
                            $conflictTime = date('H:i', $conflict->start_time) . '-' . date('H:i', $conflict->end_time);
                            return [
                                'code' => 400,
                                'msg' => "Room {$data['room']} is already booked during {$conflictTime} on {$currentDate}",
                                'state' => 'CONFLICT'
                            ];
                        }

                        $scheduleData[] = [
                            'studios_id' => $data['studios_id'],
                            'category_id' => $data['category_id'],
                            'level_id' => $data['level_id'],
                            'subject_id' => $data['subject_id'],
                            'lesson_id' => $lesson_id,
                            'lesson_codes' => $lessonCode,
                            'number_lesson' => $data['number_lesson'],
                            'teacher_id' => $data['teacher_id'],
                            'date' => $currentDate,
                            'class_id' => $data['class_id'],
                            'room' => $data['room'],
                            'start' => $data['start'],
                            'end' => $data['end'],
                            'start_time' => $startTimestamp,
                            'end_time' => $endTimestamp,
                            'scene' => 1,
                        ];

                        // 下一天
                        $currentDate = date('Y-m-d', strtotime($currentDate . ' +1 day'));
                    }

                    // 批量插入
                    $result = \app\admin\model\Schedule::insertAll($scheduleData);
                    Db::commit();

                    return ['code' => 200, 'msg' => 'Schedule generated successfully', 'state' => 'OK', 'data' => $result];

                } catch (\Exception $e) {
                    Db::rollback();
                    return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR'];
                }
            }

            // 按周排课
            if($data['repetition_method'] == 'week'){
                // 初始化变量
                $baseCode = $data['lesson_codes'];
                $scheduleData = [];
                $currentDate = $data['date'];
                $weekRules = $data['week'];
                $totalCycles = count($weekRules); // 直接使用week数组长度作为总周期数
                $currentCycle = 0;
                $processedLessons = 0;

                // 星期英文名到缩写的映射
                $dayAbbreviations = [
                    'Monday' => 'M',
                    'Tuesday' => 'T',
                    'Wednesday' => 'W',
                    'Thursday' => 'TH',
                    'Friday' => 'F',
                    'Saturday' => 'SA',
                    'Sunday' => 'SU'
                ];

                try {
                    Db::startTrans();

                    // 自动推算结束条件：完成所有week周期
                    while ($currentCycle < $totalCycles) {
                        $currentDayName = date('l', strtotime($currentDate));
                        $currentWeekRule = $weekRules[$currentCycle];

                        // 检查当前日期是否在当前周期的排课日中
                        $scheduleDays = array_map('trim', explode(',', $currentWeekRule));
                        if (in_array($currentDayName, $scheduleDays)) {
                            // 生成课程代码
                            $lessonCode = preg_replace('/-W\d+/', '-W'.($currentCycle+1), $baseCode).'-'.$dayAbbreviations[$currentDayName];

                            // 检查时间冲突
                            $startTime = strtotime($currentDate . ' ' . $data['start']);
                            $endTime = strtotime($currentDate . ' ' . $data['end']);

                            $conflict = \app\admin\model\Schedule::where([
                                'room' => $data['room'],
                                'date' => $currentDate
                            ])->where(function($query) use ($startTime, $endTime) {
                                // 新课程开始时间在已有课程时间段内
                                $query->where('start_time', 'between', [$startTime, $endTime])
                                    ->whereOr('end_time', 'between', [$startTime, $endTime]);// 新课程结束时间在已有课程时间段内
                            })->find();

                            if ($conflict) {
                                Db::rollback();
                                $conflictTime = date('H:i', $conflict->start_time).'-'.date('H:i', $conflict->end_time);
                                return [
                                    'code' => 400,
                                    'msg' => "Room {$data['room']} is already booked during {$conflictTime} on {$currentDate}",
                                    'state' => 'CONFLICT'
                                ];
                            }

                            $scheduleData[] = [
                                'scene' => 1,
                                'studios_id' => $data['studios_id'],
                                'category_id' => $data['category_id'],
                                'level_id' => $data['level_id'],
                                'subject_id' => $data['subject_id'],
                                'lesson_codes' => $lessonCode,
                                'number_lesson' => $data['number_lesson'],
                                'teacher_id' => $data['teacher_id'],
                                'date' => $currentDate,
                                'class_id' => $data['class_id'],
                                'room' => $data['room'],
                                'start' => $data['start'],
                                'end' => $data['end'],
                                'start_time' => $startTime,
                                'end_time' => $endTime,
//                                'cycle_number' => $currentCycle + 1
                            ];

                            $processedLessons++;
                        }

                        // 移动到下一天
                        $currentDate = date('Y-m-d', strtotime($currentDate . ' +1 day'));

                        // 周日时周期计数增加
                        if ($currentDayName == 'Sunday') {
                            $currentCycle++;
                        }
                    }
//                    return $scheduleData;
                    // 批量插入
                    $result = \app\admin\model\Schedule::insertAll($scheduleData);
                    Db::commit();

                    // 自动计算实际结束日期
                    $endDate = date('Y-m-d', strtotime($currentDate . ' -1 day'));

                    return ['code' => 200, 'msg' => 'Schedule generated successfully','state' => 'OK', 'data' => $result];

                } catch (\Exception $e) {
                    Db::rollback();
                    return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(),'state' => 'DATABASE_ERROR'];
                }

            }


            Db::commit();
        }
        catch (\Exception $e) {
            Db::rollback();
//            return $e->getMessage();
            return ['code'=>400, 'msg' => 'Database error: ' . $e->getMessage(), 'state'=>'DATABASE_ERROR', 'data'=>null];
        }
        return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>''];
    }

    // 编辑
    public static function edit($data)
    {
// 验证规则
        $validate = new Validate([
            'id' => 'require',
            'studios_id' => 'require',
            'category_id' => 'require',
            'level_id' => 'require',
            'subject_id' => 'require',
            'lesson_codes' => 'require',
            'number_lesson' => 'require',
            'teacher_id' => 'require',
            'date' => 'require',
            'class_id' => 'require',
            'room' => 'require',
            'start' => 'require',
            'end' => 'require',
        ], [
            'id.require' => 'ID is not empty',
            'studios_id.require' => 'StudiosId is not empty',
            'category_id.require' => 'CategoryId is not empty',
            'level_id.require' => 'LevelId is not empty',
            'subject_id.require' => 'SubjectId is not empty',
            'lesson_codes.require' => 'Lesson Codes is not empty',
            'number_lesson.require' => 'Number Lesson is not empty',
            'teacher_id.require' => 'Teacher Id is not empty',
            'date.require' => 'Date is not empty',
            'class_id.require' => 'ClassId is not empty',
            'room.require' => 'Room is not empty',
            'start.require' => 'Start Time is not empty',
            'end.require' => 'End Time is not empty',
        ]);
        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }
        try {
            $result = \app\admin\model\Schedule::update($data, ['id' => $data['id']]);
            if ($result) {
                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            }
        }
        catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }

    // 删除
    public static function del($data)
    {
        $auth = Auth::instance();
        // 验证$data['id']是否为空且为数字

        if (empty($data['id']) || !is_numeric($data['id'])) {
            return ['code'=>400, 'msg'=>'Invalid parameters', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务删除数据
        try {
            $result = \app\admin\model\Schedule::destroy($data['id']);

            if($result){
                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            }else{
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }
        }
        catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }

    // 下拉查询
    public static function select($data)
    {
        $studio = \app\admin\model\StudentLessonCodes::where(['category_id'=>$data['category_id'],'semester_id'=>$data['semester_id']])->field('lesson_id,code,lesson_rang,code_type')->order('lesson_id', 'asc')
            ->select();
        return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$studio];
    }

    // 获取指定日期的课表
    public static function getDailySchedule($date, $studios_id, $teacher_id = 0)
    {
        // 验证场馆ID
        if (!$studios_id) {
            return ['code' => 400, 'msg' => 'Invalid studio ID', 'state' => 'INVALID_ARGUMENT', 'data' => null];
        }else{
            $where['studios_id'] = $studios_id;
        }

        // 验证日期格式
        if (!strtotime($date)) {
            return ['code' => 400, 'msg' => 'Invalid date format', 'state' => 'INVALID_ARGUMENT', 'data' => null];
        }

        if($teacher_id){
            // 通过teacher_id查询用户数据
            $user = \app\admin\model\User::where(['id' => $teacher_id])->find();

            // 初始化where条件
            $where = ['studios_id' => $studios_id];

            if ($user && $user['group_id']) {
                // 查询用户组名称
                $userGroup = \app\admin\model\UserGroup::where(['id' => $user['group_id']])->value('name');

                // 只有当用户组不是Admin和Principal时才添加teacher_id条件
                if (!in_array($userGroup, ['Admin', 'Principal'])) {
                    $where['teacher_id'] = $teacher_id;
                }
            } else {
                // 如果查询不到用户或用户组，默认添加teacher_id条件
                $where['teacher_id'] = $teacher_id;
            }
        }
//        return $where;
        $list = \app\admin\model\Schedule::where($where)
            ->whereTime('start_time', '>=', $date . ' 00:00:00')
            ->whereTime('start_time', '<=', $date . ' 23:59:59')
            ->field('id,start as start_time,end as end_time,date,teacher_id,lesson_codes,level_id,studios_id,category_id,room,class_id')
            ->select();
        if($list){
            $Schedule = [];
            foreach($list as $k=>$item){
                $studios = \app\admin\model\Studios::where(['id'=>$item['studios_id']])->find();
                if(!$studios){
                    $studios = '';
                }
                $teacher = \app\admin\model\User::where(['id'=>$item['teacher_id']])->find();
                if(!$teacher){
                    $teacher = '';
                }
                $category = \app\admin\model\StudentCourseCategory::where(['category_id'=>$item['category_id']])->find();
                if(!$category){
                    $category = '';
                }
                $course = \app\admin\model\Course::where(['course_id'=>$category['course_id']])->find();
                if(!$course){
                    $course = '';
                }
                $class = \app\admin\model\Classes::where(['class_id'=>$item['class_id']])->find();
                if(!$class){
                    $class = '';
                }
                if(isset($course['course_name']) && $course['course_name'] == 'Appointment'){
                    $type = 1;
                }else{
                    $type = 1;
                }
                if(strtotime($item['end_time']) <=  time()){
                    $staus = 2;
                }else{
                    $staus = 1;
                }
                $timePeriod = $item['start_time'] . '-' . $item['end_time'];
                $time_long = bcdiv(strtotime($item['end_time']) - strtotime($item['start_time']), 3600, 1);
                $Schedule[$k] =  [
                    'start_time'=>$item['start_time'],
                    'end_time'=>$item['end_time'],
                    'child' => [
                        'date'=>$item['date'],
                        'status' => $staus,
                        'timePeriod' => $timePeriod,
                        'course' => $item['lesson_codes'],
                        'class' => isset($teacher['english_name']) && $teacher['english_name'] ? $teacher['english_name'] : '',
                        'room' => $item['room'],
                        'teacher' => isset($teacher['english_name']) && $teacher['english_name'] ? $teacher['english_name'] : '',
                        'studios' => isset($studios['studio_name']) && $studios['studio_name'] ? $studios['studio_name'] : '',
                        'type' => isset($type) && $type ? $type : '',
                        'time_long' => $time_long
                    ],
                ];
            }
        }else{
            $Schedule = [
            ];
        }
        return [
            'code' => 200,
            'msg' => 'Successful',
            'state' => 'OK',
            'data' => $Schedule
        ];
    }

    // 获取指定日期的周课表
    public static function getWeeklySchedule($date, $studios_id, $teacher_id = 0)
    {
        // 验证场馆ID
        if (!$studios_id) {
            return ['code' => 400, 'msg' => 'Invalid studio ID', 'state' => 'INVALID_ARGUMENT', 'data' => null];
        }else{
            $where['studios_id'] = $studios_id;
        }

        // 验证日期格式
        if (!strtotime($date)) {
            return ['code' => 400, 'msg' => 'Invalid date format', 'state' => 'INVALID_ARGUMENT', 'data' => null];
        }

        if($teacher_id){
            // 通过teacher_id查询用户数据
            $user = \app\admin\model\User::where(['id' => $teacher_id])->find();

            // 初始化where条件
            $where = ['studios_id' => $studios_id];

            if ($user && $user['group_id']) {
                // 查询用户组名称
                $userGroup = \app\admin\model\UserGroup::where(['id' => $user['group_id']])->value('name');

                // 只有当用户组不是Admin和Principal时才添加teacher_id条件
                if (!in_array($userGroup, ['Admin', 'Principal'])) {
                    $where['teacher_id'] = $teacher_id;
                }
            } else {
                // 如果查询不到用户或用户组，默认添加teacher_id条件
                $where['teacher_id'] = $teacher_id;
            }
        }

        try {
            // 计算本周周一和周日日期
            $timestamp = strtotime($date);
            $monday = date('Y-m-d', strtotime('monday this week', $timestamp));
            $sunday = date('Y-m-d', strtotime('sunday this week', $timestamp));

            // 查询本周课程数据
            $weeklySchedule = \app\admin\model\Schedule::where($where)
                ->whereBetween('date', [$monday, $sunday])
                ->order('date asc, start_time asc')
                ->select();

            // 按日期分组整理数据
            $result = [];
            foreach ($weeklySchedule as $schedule) {
                $day = date('N', strtotime($schedule['date'])); // 1-7表示周一到周日

                $studios = \app\admin\model\Studios::where(['id'=>$schedule['studios_id']])->find();
                if(!$studios){
                    $studios = '';
                }
                $teacher = \app\admin\model\User::where(['id'=>$schedule['teacher_id']])->find();
                if(!$teacher){
                    $teacher = '';
                }
                $category = \app\admin\model\StudentCourseCategory::where(['category_id'=>$schedule['category_id']])->find();
                if(!$category){
                    $category = '';
                }
                $course = \app\admin\model\Course::where(['course_id'=>$category['course_id']])->find();
                if(!$course){
                    $course = '';
                }
                if(isset($course['course_name']) && $course['course_name'] == 'Appointment'){
                    $type = 1;
                }else{
                    $type = 1;
                }
                if(strtotime($schedule['end_time']) <=  time()){
                    $staus = 2;
                }else{
                    $staus = 1;
                }
                $timePeriod = $schedule['start_time'] . '-' . $schedule['end_time'];
                $time_long = bcdiv(strtotime($schedule['end_time']) - strtotime($schedule['start_time']), 3600, 1);
//                $Schedule[$k] =  ,
//                ];


                $result[$day][] = [
                    [
                        'start_time'=>$schedule['start_time'],
                        'end_time'=>$schedule['end_time'],
                        'child' => [
                            'date'=>$schedule['date'],
                            'status' => $staus,
                            'timePeriod' => $timePeriod,
                            'course' => $schedule['lesson_codes'],
                            'teacher' => isset($teacher['english_name']) && $teacher['english_name'] ? $teacher['english_name'] : '',
                            'studios' => isset($studios['studio_name']) && $studios['studio_name'] ? $studios['studio_name'] : '',
                            'type' => isset($type) && $type ? $type : '',
                            'time_long' => $time_long
                        ]
                    ]
                ];
            }

            // 确保每天都有数据，即使为空数组
            for ($i = 1; $i <= 7; $i++) {
                if (!isset($result[$i])) {
                    $result[$i] = [];
                }
            }

            return [
                'code' => 200,
                'msg' => 'Successful',
                'state' => 'OK',
                'data' => [
                    'week_range' => ['monday' => $monday, 'sunday' => $sunday],
                    'schedules' => $result
                ]
            ];
        } catch (\Exception $e) {
            return [
                'code' => 400,
                'msg' => 'Database error: ' . $e->getMessage(),
                'state' => 'DATABASE_ERROR',
                'data' => null
            ];
        }
    }

    // 获取指定日期的月课表
    public static function getMonthlySchedule($date, $studios_id, $teacher_id = 0)
    {
        if (!$studios_id) {
            return ['code' => 400, 'msg' => 'Invalid studio ID', 'state' => 'INVALID_ARGUMENT', 'data' => null];
        }else{
            $where['studios_id'] = $studios_id;
        }

        // 验证日期格式
        if (!strtotime($date)) {
            return ['code' => 400, 'msg' => 'Invalid date format', 'state' => 'INVALID_ARGUMENT', 'data' => null];
        }

        if($teacher_id){
            // 通过teacher_id查询用户数据
            $user = \app\admin\model\User::where(['id' => $teacher_id])->find();

            // 初始化where条件
            $where = ['studios_id' => $studios_id];

            if ($user && $user['group_id']) {
                // 查询用户组名称
                $userGroup = \app\admin\model\UserGroup::where(['id' => $user['group_id']])->value('name');

                // 只有当用户组不是Admin和Principal时才添加teacher_id条件
                if (!in_array($userGroup, ['Admin', 'Principal'])) {
                    $where['teacher_id'] = $teacher_id;
                }
            } else {
                // 如果查询不到用户或用户组，默认添加teacher_id条件
                $where['teacher_id'] = $teacher_id;
            }
        }

        try {
            // 计算当月第一天和最后一天日期
            $timestamp = strtotime($date);
            $firstDay = date('Y-m-01', $timestamp);
            $lastDay = date('Y-m-t', $timestamp);
            $totalDays = date('t', $timestamp); // 当月总天数

            // 初始化结果数组，确保所有日期都有空数组
            $result = [];
            for ($day = 1; $day <= $totalDays; $day++) {
                $result[$day] = [];
            }

            // 查询当月课程数据
            $monthlySchedule = \app\admin\model\Schedule::where($where)
                ->whereBetween('date', [$firstDay, $lastDay])
                ->order('date asc, start_time asc')
                ->select();

            foreach ($monthlySchedule as $schedule) {
                $day = date('j', strtotime($schedule['date']));

                $studios = \app\admin\model\Studios::where(['id'=>$schedule['studios_id']])->find();
                $teacher = \app\admin\model\User::where(['id'=>$schedule['teacher_id']])->find();
                $category = \app\admin\model\StudentCourseCategory::where(['category_id'=>$schedule['category_id']])->find();
                $course = $category ? \app\admin\model\Course::where(['course_id'=>$category['course_id']])->find() : null;

                $type = (isset($course['course_name']) && $course['course_name'] == 'Appointment') ? 1 : 1;
                $staus = (strtotime($schedule['end_time']) <= time()) ? 2 : 1;
                $timePeriod = $schedule['start_time'] . '-' . $schedule['end_time'];
                $time_long = bcdiv(strtotime($schedule['end_time']) - strtotime($schedule['start_time']), 3600, 1);

                $result[$day][] = [
                    [
                        'start_time' => $schedule['start_time'],
                        'end_time' => $schedule['end_time'],
                        'child' => [
                            'date' => $schedule['date'],
                            'status' => $staus,
                            'timePeriod' => $timePeriod,
                            'course' => $schedule['lesson_codes'],
                            'teacher' => isset($teacher['english_name']) ? $teacher['english_name'] : '',
                            'studios' => isset($studios['studio_name']) ? $studios['studio_name'] : '',
                            'type' => $type,
                            'time_long' => $time_long
                        ]
                    ]
                ];
            }

            return [
                'code' => 200,
                'msg' => 'Successful',
                'state' => 'OK',
                'data' => [
                    'month_range' => ['first_day' => $firstDay, 'last_day' => $lastDay],
                    'schedules' => $result
                ]
            ];
        }
        catch (\Exception $e) {
            return [
                'code' => 400,
                'msg' => 'Database error: ' . $e->getMessage() . ' at line ' . $e->getLine(),
                'state' => 'DATABASE_ERROR',
                'data' => null
            ];
        }

    }

    // 获取指定日期的学期课表
    public static function getSemesterSchedule($date, $studios_id, $teacher_id = 0)
    {
        if (!$studios_id) {
            return ['code' => 400, 'msg' => 'Invalid studio ID', 'state' => 'INVALID_ARGUMENT', 'data' => null];
        }else{
            $where['studios_id'] = $studios_id;
        }

        // 验证日期格式
        if (!strtotime($date)) {
            return ['code' => 400, 'msg' => 'Invalid date format', 'state' => 'INVALID_ARGUMENT', 'data' => null];
        }

        if($teacher_id){
            // 通过teacher_id查询用户数据
            $user = \app\admin\model\User::where(['id' => $teacher_id])->find();

            // 初始化where条件
            $where = ['studios_id' => $studios_id];

            if ($user && $user['group_id']) {
                // 查询用户组名称
                $userGroup = \app\admin\model\UserGroup::where(['id' => $user['group_id']])->value('name');

                // 只有当用户组不是Admin和Principal时才添加teacher_id条件
                if (!in_array($userGroup, ['Admin', 'Principal'])) {
                    $where['teacher_id'] = $teacher_id;
                }
            } else {
                // 如果查询不到用户或用户组，默认添加teacher_id条件
                $where['teacher_id'] = $teacher_id;
            }
        }

        try {
            // 解析输入日期
            $inputDate = strtotime($date);
            $inputYear = date('Y', $inputDate);

            // 定义学期时间段
            $semester1Start = strtotime($inputYear.'-09-01');
            $semester1End = strtotime(($inputYear+1).'-01-31');
            $semester2Start = strtotime($inputYear.'-02-26');
            $semester2End = strtotime($inputYear.'-07-13');

            // 检查当前日期是否在学期内
            $isSemester1 = ($inputDate >= $semester1Start && $inputDate <= $semester1End);
            $isSemester2 = ($inputDate >= $semester2Start && $inputDate <= $semester2End);

            if (!$isSemester1 && !$isSemester2) {
                return [
                    'code' => 200,
                    'msg' => 'Currently on vacation',
                    'state' => 'VACATION',
                    'data' => []
                ];
            }

            // 确定学期时间段
            if ($isSemester1) {
                $startDate = date('Y-m-d', $semester1Start);
                $endDate = date('Y-m-d', $semester1End);
            } else {
                $startDate = date('Y-m-d', $semester2Start);
                $endDate = date('Y-m-d', $semester2End);
            }

            // 计算总天数
            $totalDays = (strtotime($endDate) - strtotime($startDate)) / (60 * 60 * 24) + 1;

            // 初始化结果数组，确保所有日期都有记录
            $result = [];
            $currentDate = $startDate;
            for ($i = 0; $i < $totalDays; $i++) {
                $dayKey = date('Y-m-d', strtotime($currentDate));
                $result[$dayKey] = [];
                $currentDate = date('Y-m-d', strtotime($currentDate . ' +1 day'));
            }

            // 查询学期课程数据
            $semesterSchedule = \app\admin\model\Schedule::where($where)
                ->whereBetween('date', [$startDate, $endDate])
                ->order('date asc, start_time asc')
                ->select();

            // 整理课程数据
            foreach ($semesterSchedule as $schedule) {
                $dayKey = $schedule['date'];

                $studios = \app\admin\model\Studios::where(['id'=>$schedule['studios_id']])->find();
                $teacher = \app\admin\model\User::where(['id'=>$schedule['teacher_id']])->find();
                $category = \app\admin\model\StudentCourseCategory::where(['category_id'=>$schedule['category_id']])->find();
                $course = $category ? \app\admin\model\Course::where(['course_id'=>$category['course_id']])->find() : null;

                $type = (isset($course['course_name']) && $course['course_name'] == 'Appointment') ? 1 : 1;
                $staus = (strtotime($schedule['end_time']) <= time()) ? 2 : 1;
                $timePeriod = $schedule['start_time'] . '-' . $schedule['end_time'];
                $time_long = bcdiv(strtotime($schedule['end_time']) - strtotime($schedule['start_time']), 3600, 1);

                $result[$dayKey][] = [
                    'start_time' => $schedule['start_time'],
                    'end_time' => $schedule['end_time'],
                    'child' => [
                        'date' => $schedule['date'],
                        'status' => $staus,
                        'timePeriod' => $timePeriod,
                        'course' => $schedule['lesson_codes'],
                        'teacher' => isset($teacher['english_name']) ? $teacher['english_name'] : '',
                        'studios' => isset($studios['studio_name']) ? $studios['studio_name'] : '',
                        'type' => $type,
                        'time_long' => $time_long
                    ]
                ];
            }

            return [
                'code' => 200,
                'msg' => 'Successful',
                'state' => 'OK',
                'data' => [
                    'semester_range' => ['start_date' => $startDate, 'end_date' => $endDate],
                    'schedules' => $result
                ]
            ];

        } catch (\Exception $e) {
            return [
                'code' => 400,
                'msg' => 'Database error: ' . $e->getMessage(),
                'state' => 'DATABASE_ERROR',
                'data' => null
            ];
        }
    }



}
